{% extends "base/nav.html" %}
{% load static %}

{% block title %}{{ attraction.name }} - 旅游舆情监测{% endblock %}

{% block css %}
    <style>
        .comments-container {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            max-height: 600px;
            overflow-y: auto;
            padding: 20px;
            margin-bottom: 2rem;
        }

        .comment-item {
            border: 1px solid #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background: #fafbfc;
            transition: all 0.3s ease;
        }

        .comment-item:hover {
            background: #f1f3f4;
            border-color: #e9ecef;
        }

        .comment-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 10px;
        }

        .comment-user-info {
            flex: 1;
        }

        .comment-actions {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .comment-content {
            margin: 10px 0;
            line-height: 1.5;
            color: #333;
        }

        .children-comments {
            margin-left: 30px;
            border-left: 3px solid #dee2e6;
            padding-left: 15px;
        }

        .child-comment {
            background: white;
            border: 1px solid #e9ecef;
        }

        @media (max-width: 768px) {
            .comments-container {
                max-height: 400px;
                padding: 15px;
            }

            .comment-header {
                flex-direction: column;
                gap: 10px;
            }

            .comment-actions {
                align-self: flex-end;
            }
        }

        .attraction-header {
            background: linear-gradient(135deg, #1e88e5 0%, #0d47a1 100%);
            color: white;
            padding: 3rem 0;
            margin-bottom: 2rem;
            border-radius: 0 0 20px 20px;
        }

        .attraction-meta {
            opacity: 0.9;
            font-size: 0.95em;
        }

        .attraction-content {
            line-height: 1.8;
            font-size: 1.1em;
            color: #333;
        }

        .attraction-content img {
            max-width: 100%;
            height: auto;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            margin: 1.5rem 0;
        }

        .collect-section {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
            border: 1px solid #e9ecef;
        }

        .collect-btn-wrapper {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .collect-image-btn {
            cursor: pointer;
            transition: all 0.3s ease;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 50px;
            height: 50px;
            border: none;
            background: transparent;
        }

        .collect-image-btn:hover {
            transform: scale(1.1);
        }

        #collect-image {
            border-radius: 50%;
            transition: all 0.3s ease;
            object-fit: cover;
            width: 100%;
            height: 100%;
        }

        .action-buttons {
            display: flex;
            gap: 1rem;
            margin-top: 2rem;
            flex-wrap: wrap;
        }

        .attraction-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        .badge-custom {
            background: linear-gradient(45deg, #1e88e5, #0d47a1);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 20px;
        }

        .sentiment-stats {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 3px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 2rem;
        }

        .sentiment-score {
            font-size: 3rem;
            font-weight: bold;
            text-align: center;
            margin-bottom: 1rem;
        }

        .sentiment-labels {
            display: flex;
            justify-content: space-between;
            font-size: 0.9em;
            color: #666;
        }

        /* 修复评分星星样式 */
        .rating-stars {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }

        .rating-stars input[type="radio"] {
            display: none;
        }

        .rating-stars .star-label {
            cursor: pointer;
            color: #ddd;
            font-size: 24px;
            transition: color 0.2s;
        }

        .rating-stars input[type="radio"]:checked + .star-label,
        .rating-stars .star-label:hover,
        .rating-stars input[type="radio"]:checked ~ .star-label {
            color: #ffc107;
        }

        /* 评论表单样式 */
        .comment-form .form-group {
            margin-bottom: 1.5rem;
        }

        .comment-form .form-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
            display: block;
        }
    </style>
{% endblock %}

{% block content %}
    <!-- 景点头部 -->
    <div class="attraction-header">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 mx-auto text-center">
                    <h1 class="display-4 mb-3">{{ attraction.name }}</h1>
                    <div class="attraction-meta">
                        <span class="me-3">
                            <i class="fa fa-map-marker"></i> {{ attraction.location }}
                        </span>
                        <span class="me-3">
                            <i class="fa fa-calendar"></i> {{ attraction.created_at|date:"Y年m月d日" }}
                        </span>
                        {% if attraction.categories.exists %}
                            <span class="badge-custom">
                                <i class="fa fa-folder"></i> {{ attraction.categories.first.name }}
                            </span>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="row">
            <div class="col-lg-8">
                <!-- 收藏区域 -->
                <div class="collect-section">
                    <div class="collect-btn-wrapper">
                        <button class="collect-image-btn" id="collect-image-btn"
                                {% if not user.is_authenticated %}disabled title="请先登录"{% endif %}>
                            <img src="{% static 'img/heart-gray.png' %}" alt="收藏" id="collect-image">
                        </button>
                        <button class="btn btn-lg {% if user.is_authenticated %}btn-outline-danger{% else %}btn-secondary{% endif %}"
                                id="collect-btn" {% if not user.is_authenticated %}disabled{% endif %}>
                            <i class="fa fa-heart"></i>
                            <span id="collect-text">
                {% if user.is_authenticated %}收藏{% else %}请登录后收藏{% endif %}
            </span>
                            <span class="badge bg-secondary ms-2"
                                  id="collect-count">{{ attraction.collects.count }}</span>
                        </button>
                    </div>
                    <!-- 简化的调试信息 -->
                    {% if user.is_authenticated %}
                        <div class="mt-2">
                            <small class="text-muted">
                                用户: {{ user.username }} |
                                收藏数: {{ attraction.collects.count }} |
                                已收藏: {% if user_has_collected %}是{% else %}否{% endif %}
                            </small>
                        </div>
                    {% endif %}
                </div>

                <!-- 景点内容 -->
                <div class="card attraction-card mb-4">
                    <div class="card-body">
                        {% if attraction.main_image %}
                            <div class="text-center mb-4">
                                <img src="{{ attraction.main_image.url }}" alt="{{ attraction.name }}"
                                     class="img-fluid rounded" style="max-height: 400px; object-fit: cover;">
                            </div>
                        {% endif %}

                        <div class="attraction-content">
                            {{ attraction.description|safe }}
                        </div>

                        <!-- 标签区域 -->
                        {% if attraction.sentiment_tags.exists %}
                            <div class="attraction-tags mt-4">
                                <strong><i class="fa fa-tags"></i> 情感标签:</strong>
                                {% for tag in attraction.sentiment_tags.all %}
                                    <span class="badge badge-info">{{ tag.name }}</span>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <a href="{% url 'main:attraction_list' %}" class="btn btn-outline-primary">
                        <i class="fa fa-home"></i> 返回首页
                    </a>
                    <a href="{% url 'main:attraction_list' %}" class="btn btn-outline-secondary">
                        <i class="fa fa-list"></i> 景点列表
                    </a>
                    {% if user == attraction.created_by or user.is_staff %}
                        <a href="{% url 'users:attraction_update' attraction.pk %}" class="btn btn-outline-warning">
                            <i class="fa fa-edit"></i> 编辑景点
                        </a>
                    {% endif %}
                </div>
            </div>

            <!-- 右侧信息栏 -->
            <div class="col-lg-4">
                <!-- 情感统计 -->
                <div class="sentiment-stats">
                    <h4 class="text-center mb-3"><i class="fa fa-chart-pie"></i> 情感分析</h4>

                    <div class="sentiment-score text-{% if attraction.avg_sentiment_score > 0.1 %}success{% elif attraction.avg_sentiment_score < -0.1 %}danger{% else %}warning{% endif %}">
                        {{ attraction.avg_sentiment_score|floatformat:2 }}
                    </div>

                    <div class="progress mb-3" style="height: 25px;">
                        <div class="progress-bar bg-success"
                             style="width: {{ sentiment_stats.positive_percent }}%"></div>
                        <div class="progress-bar bg-warning"
                             style="width: {{ sentiment_stats.neutral_percent }}%"></div>
                        <div class="progress-bar bg-danger"
                             style="width: {{ sentiment_stats.negative_percent }}%"></div>
                    </div>

                    <div class="sentiment-labels">
                        <span>正面 {{ sentiment_stats.positive_percent|floatformat:1 }}%</span>
                        <span>中性 {{ sentiment_stats.neutral_percent|floatformat:1 }}%</span>
                        <span>负面 {{ sentiment_stats.negative_percent|floatformat:1 }}%</span>
                    </div>
                </div>

                <!-- 景点信息 -->
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fa fa-info-circle"></i> 景点信息</h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <td><strong>城市:</strong></td>
                                <td>{{ attraction.city }}</td>
                            </tr>
                            <tr>
                                <td><strong>省份:</strong></td>
                                <td>{{ attraction.province }}</td>
                            </tr>
                            <tr>
                                <td><strong>热度:</strong></td>
                                <td><span class="badge badge-info">{{ attraction.heat_index }}</span></td>
                            </tr>
                            <tr>
                                <td><strong>评论数:</strong></td>
                                <td>{{ attraction.review_count }}</td>
                            </tr>
                            <tr>
                                <td><strong>收藏数:</strong></td>
                                <td>{{ attraction.collects.count }}</td>
                            </tr>
                            <tr>
                                <td><strong>状态:</strong></td>
                                <td>
                                    {% if attraction.status == 'published' %}
                                        <span class="badge badge-success">已发布</span>
                                    {% elif attraction.status == 'draft' %}
                                        <span class="badge badge-secondary">草稿</span>
                                    {% else %}
                                        <span class="badge badge-warning">待审核</span>
                                    {% endif %}
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 评论区域 -->
        <div class="row mt-5">
            <div class="col-12">
                <div class="comments-container">
                    <h4 class="mb-3"><i class="fa fa-comments me-2"></i>用户评论</h4>

                    {% for comment in root_comments %}
                        <div class="comment-item card mb-3">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <strong class="text-primary">{{ comment.author.username }}</strong>
                                        <small class="text-muted ms-2">{{ comment.created_at|date:"Y-m-d H:i" }}</small>
                                        <span class="badge
                                    {% if comment.sentiment_type == 'positive' %}bg-success
                                    {% elif comment.sentiment_type == 'negative' %}bg-danger
                                    {% else %}bg-secondary{% endif %} ms-2">
                                    {{ comment.get_sentiment_type_display }}
                                </span>
                                        {% if comment.rating %}
                                            <span class="text-warning ms-2">
                                    {% for i in "12345" %}
                                        {% if forloop.counter <= comment.rating %}
                                            <i class="fas fa-star"></i>
                                        {% else %}
                                            <i class="far fa-star"></i>
                                        {% endif %}
                                    {% endfor %}
                                </span>
                                        {% endif %}
                                    </div>
                                    <div class="comment-actions">
                                        {% if user.is_authenticated %}
                                            <button class="btn-reply btn btn-sm btn-outline-primary"
                                                    data-comment-id="{{ comment.id }}"
                                                    data-username="{{ comment.author.username }}">
                                                <i class="fas fa-reply"></i> 回复
                                            </button>
                                        {% endif %}
                                        {% if comment.author == user or user.is_staff %}
                                            <a href="{% url 'main:delete_comment' comment.id %}"
                                               class="btn btn-sm btn-outline-danger"
                                               onclick="return confirm('确定删除这条评论吗？')">
                                                <i class="fas fa-trash"></i> 删除
                                            </a>
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="comment-content">
                                    <p class="mb-2">{{ comment.content }}</p>
                                </div>

                                <!-- 显示回复 -->
                                {% for reply in comment.replies.all %}
                                    {% if reply.is_active %}
                                        <div class="reply-item card mt-2 ms-4 bg-light">
                                            <div class="card-body py-2">
                                                <div class="d-flex justify-content-between">
                                                    <small>
                                                        <strong>{{ reply.author.username }}</strong>
                                                        <span class="text-muted ms-2">回复</span>
                                                    </small>
                                                    <small class="text-muted">{{ reply.created_at|date:"m-d H:i" }}</small>
                                                </div>
                                                <p class="mb-0 small">{{ reply.content }}</p>
                                            </div>
                                        </div>
                                    {% endif %}
                                {% endfor %}
                            </div>
                        </div>
                    {% empty %}
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-comments fa-2x mb-2"></i>
                            <p>暂无评论，快来发表第一条评论吧！</p>
                        </div>
                    {% endfor %}
                </div>

                <!-- 评论表单 - 修复版 -->
                <div class="comment-form mt-5">
                    <h4>发表评论</h4>
                    {% if user.is_authenticated %}
                        <form method="post" action="{% url 'main:add_comment' attraction.pk %}" id="comment-form">
                            {% csrf_token %}
                            <input type="hidden" name="parent" id="parent_id" value="">
                            <input type="hidden" name="source_platform" value="website">

                            <!-- 评论内容 -->
                            <div class="form-group mb-3">
                                <label for="content" class="form-label">评论内容：</label>
                                <textarea name="content" id="content" class="form-control" rows="4"
                                          placeholder="请输入评论内容..." required></textarea>
                            </div>

                            <!-- 评分 -->
                            <div class="form-group mb-3">
                                <label class="form-label">评分：</label>
                                <div class="rating-stars">
                                    <input type="radio" id="star1" name="rating" value="1" required>
                                    <label for="star1" class="star-label">★</label>

                                    <input type="radio" id="star2" name="rating" value="2">
                                    <label for="star2" class="star-label">★</label>

                                    <input type="radio" id="star3" name="rating" value="3">
                                    <label for="star3" class="star-label">★</label>

                                    <input type="radio" id="star4" name="rating" value="4">
                                    <label for="star4" class="star-label">★</label>

                                    <input type="radio" id="star5" name="rating" value="5">
                                    <label for="star5" class="star-label">★</label>
                                </div>
                            </div>

                            <!-- 情感倾向 -->
                            <div class="form-group mb-3">
                                <label for="sentiment_type" class="form-label">情感倾向：</label>
                                <select name="sentiment_type" id="sentiment_type" class="form-select" required>
                                    <option value="positive">正面</option>
                                    <option value="neutral" selected>中性</option>
                                    <option value="negative">负面</option>
                                </select>
                            </div>

                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-paper-plane me-2"></i>提交评论
                            </button>
                        </form>
                    {% else %}
                        <div class="alert alert-info">
                            请<a href="{% url 'users:login' %}">登录</a>后发表评论
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            console.log('=== 收藏功能启动 ===');

            const collectBtn = document.getElementById('collect-btn');
            const collectImageBtn = document.getElementById('collect-image-btn');
            const collectImage = document.getElementById('collect-image');
            const collectText = document.getElementById('collect-text');
            const collectCount = document.getElementById('collect-count');

            // 调试：记录初始状态
            console.log('页面加载时元素状态:', {
                collectBtn: collectBtn ? collectBtn.className : 'null',
                collectImage: collectImage ? collectImage.src : 'null',
                collectText: collectText ? collectText.textContent : 'null'
            });

            {% if user.is_authenticated %}
                // 立即锁定初始状态 - 使用IIFE确保立即执行
                (function initializeCollectState() {
                    console.log('开始初始化收藏状态...');

                    const initialCollected = {% if user_has_collected %}true{% else %}false{% endif %};
                    const initialCount = {{ attraction.collects.count|default:0 }};

                    console.log('服务器状态:', {
                        collected: initialCollected,
                        count: initialCount
                    });

                    // 强制设置初始状态
                    if (collectImage) {
                        collectImage.src = initialCollected ?
                            "{% static 'img/heart-red.png' %}" :
                            "{% static 'img/heart-gray.png' %}";
                        console.log('设置图片:', collectImage.src);
                    }

                    if (collectBtn) {
                        collectBtn.className = initialCollected ?
                            'btn btn-lg btn-danger collect-btn' :  // 添加collect-btn类
                            'btn btn-lg btn-outline-danger collect-btn';
                        console.log('设置按钮类:', collectBtn.className);
                    }

                    if (collectText) {
                        collectText.textContent = initialCollected ? '已收藏' : '收藏';
                        console.log('设置文本:', collectText.textContent);
                    }

                    if (collectCount) {
                        collectCount.textContent = initialCount;
                        console.log('设置数量:', collectCount.textContent);
                    }

                    console.log('初始化完成');
                })();

                // 收藏切换功能
                function toggleCollect() {
                    console.log('点击收藏按钮');

                    const formData = new FormData();
                    formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

                    fetch('{% url "collect:toggle_collect" attraction.pk %}', {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': '{{ csrf_token }}',
                        },
                        body: formData
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log('AJAX响应:', data);
                            if (data.success) {
                                // 更新UI
                                if (collectImage) {
                                    collectImage.src = data.collected ?
                                        "{% static 'img/heart-red.png' %}" :
                                        "{% static 'img/heart-gray.png' %}";
                                }
                                if (collectBtn) {
                                    collectBtn.className = data.collected ?
                                        'btn btn-lg btn-danger collect-btn' :
                                        'btn btn-lg btn-outline-danger collect-btn';
                                }
                                if (collectText) {
                                    collectText.textContent = data.collected ? '已收藏' : '收藏';
                                }
                                if (collectCount) {
                                    collectCount.textContent = data.collect_count;
                                }
                            }
                        })
                        .catch(error => {
                            console.error('收藏错误:', error);
                        });
                }

                // 绑定事件
                if (collectBtn) {
                    collectBtn.addEventListener('click', toggleCollect);
                }
                if (collectImageBtn) {
                    collectImageBtn.addEventListener('click', toggleCollect);
                }

            {% endif %}

            // 评分功能 - 修复版
            const ratingStars = document.querySelectorAll('.rating-stars input');
            const starLabels = document.querySelectorAll('.star-label');

            // 初始化星星颜色
            starLabels.forEach(label => {
                label.style.color = '#ddd';
            });

            ratingStars.forEach(star => {
                star.addEventListener('change', function () {
                    const rating = parseInt(this.value);

                    // 更新星星显示
                    starLabels.forEach((label, index) => {
                        if (index < rating) {
                            label.style.color = '#ffc107';
                        } else {
                            label.style.color = '#ddd';
                        }
                    });
                });
            });

            // 回复功能
            const replyButtons = document.querySelectorAll('.btn-reply');
            const parentInput = document.getElementById('parent_id');

            replyButtons.forEach(button => {
                button.addEventListener('click', function () {
                    const commentId = this.getAttribute('data-comment-id');
                    const username = this.getAttribute('data-username');

                    // 直接跳转到回复页面
                    const replyUrl = "{% url 'main:reply_comment' 0 %}".replace('0', commentId);
                    window.location.href = replyUrl;
                });
            });
        });
    </script>
{% endblock %}